<?php

include_once dirname(__FILE__) . '/customer_order_item.php';

class Consumer_order {

    private $consumer_order_id;
    public $customer_id;
    public $create_date;
    public $order_state;
    public $finish_date;
    public $amount;
    public $remark;

    private function __construct() {
        $args_num = func_num_args(); //获取参数个数
        $args = func_get_args(); //获取参数列表

        switch ($args_num) {
            case 1:
                $this->__construct1($args[0]);
                break;
            case 2:
                $this->__construct2($args[1]);
                break;
            default:

                break;
        }
    }

    private function __construct1($id) {

        $db = Db::get_instance();
        $sql = "SELECT * FROM  fac_consumer_order where consumer_order_id=" . $id;
        $rs = $db->query($sql);
        $row = $rs[0];
        $this->consumer_order_id = $row['consumer_order_id'];
        $this->customer_id = $row['customer_id'];
        $this->create_date = $row['create_date'];
        $this->order_state = $row['order_state'];
        $this->finish_date = $row['finish_date'];
        $this->amount = $row['amount'];
        $this->remark = $row['remark'];
    }

    //根据数据库查询结果的构造函数
    private function __construct2($row) {
        $this->consumer_order_id = $row['consumer_order_id'];
        $this->customer_id = $row['customer_id'];
        $this->create_date = $row['create_date'];
        $this->order_state = $row['order_state'];
        $this->finish_date = $row['finish_date'];
        $this->amount = $row['amount'];
        $this->remark = $row['remark'];
    }

    //根据id得到一个订单对象
    public static function get_Consumer_order($id) {
        $id = intval($id);
        if (Consumer_order::id_is_exist($id))
            return new Consumer_order($id);
        else
            return false;
    }

    //根据id判断订单是否存在
    public static function id_is_exist($id) {
        $id = intval($id);
        $sql = "SELECT count(*) as num from fac_consumer_order where consumer_order_id=" . $id;
        $rs = Db::get_instance()->query($sql);

        $row = $rs[0];
        if ($row["num"] < 1)
            return false;
        else
            return true;
    }

    //获取订单id
    public function get_id() {
        return $this->consumer_order_id;
    }

    //增加一个订单
    public static function add_a_order($c_cid, $c_remark, $products, $amount, $is_delay = false) {
        if ($is_delay) {
            $is_delay = "'$is_delay'";
            $order_state = '待生产';
        } else {
            $is_delay = "NULL";
            $order_state = '待发货';
        }
        $is_proxy = intval($_POST['isorderProxy']);

        $sql = "INSERT INTO fac_consumer_order (customer_id,customer_order_code,create_date,order_state,send_date,amount,is_proxy,remark)";
        $sql.=" value ($c_cid,CONCAT('C',CEIL(NOW() + 0)),now(),'$order_state',$is_delay,'$amount',$is_proxy,'$c_remark')";

        # echo $sql;

        $order_id = Db::get_instance()->query($sql);

        if ($is_proxy > 0) {
            Db::get_instance()->query(sprintf("INSERT INTO `fac_consumer_order_proxy` (`pname`,`order_id`,`amount`) VALUES ('%s',%s,'%s');", $_POST['orderProxy'], $order_id, $_POST['amount1']));
        }

        Consumer_order::save_consumer_order_item($order_id, $products);
        return $order_id;
    }

    //保存订单条目
    public static function save_consumer_order_item($order_id, $products) {
        $sql = "DELETE fac_consumer_order_item where consumer_order_id=" . $order_id;
        Db::get_instance()->query($sql);
        $sql = "INSERT INTO fac_consumer_order_item (product_id,number,unit_price,unit_price2,consumer_order_id) values ";
        foreach ($products as $product_item) {
            $product_id = $product_item['product_id'];
            $number = $product_item ['number'];
            $unit_price = $product_item['unit_price'];
            $unit_price2 = $product_item['unit_price2'];
            $sql.="($product_id,$number,$unit_price,$unit_price2,$order_id),";
        }
        $sql = substr($sql, 0, strlen($sql) - 1);
        return Db::get_instance()->query($sql) > 0;
    }

    public static function char_state($products) {//减去成品库存
        foreach ($products as $product_item) {
            $number = $product_item ['number'];
            $product_id = $product_item['product_id'];
            $sql .= "UPDATE fac_product_mess SET number=number-$number ";
            $sql .= " WHERE product_id=$product_id ;";
        }
        $sql = substr($sql, 0, strlen($sql) - 1);
        return Db::get_instance()->query($sql) > 0;
    }

    //获取订单列表
    public static function get_orders($num_per_page, $page_index, $where = '') {
        $num1 = $page_index * $num_per_page;
        if ($num_per_page == 0) {
            $limit = '';
        } else {
            $limit = "limit $num1,$num_per_page";
        }
        $sql = "SELECT
	`fac_consumer_order`.*,`fac_customer`.*,SUM(
		`fac_consumer_order_item`.number * `fac_consumer_order_item`.unit_price
	) AS `sum`,`fac_consumer_order`.remark AS remark1,`fac_consumer_order`.order_state + 0 AS order_stateint
FROM
	`fac_consumer_order`
LEFT JOIN `fac_customer` ON fac_customer.customer_id = fac_consumer_order.customer_id
LEFT JOIN `fac_consumer_order_item` ON `fac_consumer_order_item`.consumer_order_id = `fac_consumer_order`.consumer_order_id
        $where 
        GROUP BY `fac_consumer_order`.consumer_order_id
        ORDER BY `fac_consumer_order`.create_date DESC";
        $sql.=" $limit";
        $rs = Db::get_instance()->query($sql);
        return $rs;
    }

    //获取订单列表
    public static function get_orders2($num_per_page, $page_index, $where = '') {
        $num1 = $page_index * $num_per_page;
        if ($num_per_page == 0) {
            $limit = '';
        } else {
            $limit = "limit $num1,$num_per_page";
        }
        $sql = "SELECT
            `fac_consumer_order`.amount as sum,`fac_consumer_order`.*,fp.amount as sum2,fp.pname,
        `fac_consumer_order`.remark AS remark1,`fac_consumer_order`.order_state + 0 AS order_stateint
FROM
	`fac_consumer_order`
LEFT JOIN `fac_consumer_order_proxy` fp ON fp.order_id = `fac_consumer_order`.consumer_order_id
        $where 
        GROUP BY `fac_consumer_order`.consumer_order_id
        ORDER BY `fac_consumer_order`.create_date DESC";
        $sql.=" $limit";
        $rs = Db::get_instance()->query($sql);
        return $rs;
    }

    //修改后保存订单
    public function update() {
        $sql = 'UPDATE fac_consumer_order set customer_id=' . $this->customer_id . ',';
        $sql.='create_date=\'' . $this->create_date . '\',';
        $sql.='order_state=\'' . $this->order_state . '\',';
        $sql.='amount=\'' . $this->amount . '\',';
        $sql.='remark=\'' . $this->remark . '\'';
        $sql.= ' where consumer_order_id=' . $this->consumer_order_id;
        // echo $sql;
        $rs = Db::get_instance()->query($sql);
        if (!$rs)
            return false;
        else
            return true;
    }

    public function update_state() {
        $id = intval($id);
        $sql = 'UPDATE fac_consumer_order set order_state=\'' . $this->order_state . '\'';
        $sql.=" , finish_date=now()";
        $sql.=' where consumer_order_id =' . $this->consumer_order_id;
        echo $sql;
        $rs = Db::get_instance()->query($sql);
        if ($rs)
            return true;
        else
            return false;
    }

    //删除一个订单
    public static function delete_a_consumer_order($id) {
        $id = intval($id);
        $sql = 'DELETE from fac_consumer_order where consumer_order_id =' . $id;
        $rs = Db::get_instance()->query($sql);
        if ($rs)
            return true;
        else
            return false;
    }

    //完成一个订单
    public function finish() {
        //查看是否货源充足
        if ($this->check_num() != true) {
            return false;
        };
        //修改订单状态
        $sql = "UPDATE fac_consumer_order set finish_date=now() ,order_state='已发货' where consumer_order_id=" . $this->consumer_order_id;
        $rs = Db::get_instance()->query($sql);
        if ($rs < 1) {
            return false;
        }
        //获取所有订单条目
        $sql = "SELECT * from fac_consumer_order_item where consumer_order_id=" . $this->consumer_order_id;

        $orderInfo = Db::get_instance()->query("SELECT * FROM fac_consumer_order WHERE consumer_order_id=" . $this->consumer_order_id);

        $rs = Db::get_instance()->query($sql);
        //全部增加到交易记录里面
        $sql = "INSERT INTO fac_product_record (product_id,trade_date,price,trade_number) values ";
        foreach ($rs as $row) {
            $product_id = $row['product_id'];
            $number = $row['number'];
            $unit_price = $row['unit_price'];
            $sql.="($product_id,now(),$unit_price,-$number),";
            echo $orderInfo[0]['is_proxy'];
            if ($orderInfo[0]['is_proxy'] == 0) {
                //在库存里面删减产品
                $sql2 = "UPDATE fac_product_mess set number=number-$number where product_id=" . $product_id;
                Db::get_instance()->query($sql2);
            }
        }
        $sql = substr($sql, 0, strlen($sql) - 1);

        return Db::get_instance()->query($sql) > 0;
    }

    public static function check_item($consumer_order_id) {

        $sql = "SELECT
	t1.product_id,
	t2.product_model,
	t1.number,
	t1.unit_price,
	t1.number * t1.unit_price AS total_price
FROM
	fac_consumer_order_item t1
LEFT JOIN fac_product_mess t2 ON t1.product_id = t2.product_id
WHERE
	t1.consumer_order_id =$consumer_order_id";
        return $row[0] = Db::get_instance()->query($sql);
    }

    public function check_num() {
        //查询订单中订单条目的数量
        $sql = "SELECT count(*) as num from fac_consumer_order_item where consumer_order_id=" . $this->consumer_order_id;
        $rs = Db::get_instance()->query($sql);
        $row = $rs[0];
        $order_item_number = $row['num'];

        //查询订单条目中产品数目小于库存数目的条目数量
        $sql = "SELECT count(*) as num from fac_consumer_order_item,fac_product_mess where consumer_order_id=$this->consumer_order_id ";
        $sql.=" and fac_consumer_order_item.product_id=fac_product_mess.product_id ";
        $sql.=" and fac_consumer_order_item.number<=fac_product_mess.number";
        $rs = Db::get_instance()->query($sql);
        $row = $rs[0];
        $valid_number = $row['num'];
        //判断是否相等
        if ($order_item_number == $valid_number) {
            return true;
        } else {
            return false;
        }
    }

    public static function getData($id) {
        $res = Db::get_instance()->query("SELECT *,fac_consumer_order.remark as remark1 FROM `fac_consumer_order` LEFT JOIN `fac_customer` ON `fac_customer`.customer_id = `fac_consumer_order`.customer_id WHERE `consumer_order_id` = $id;");
        return $res[0];
    }

    /**
     * 取消客户订单
     * @param type $orderId
     * @return 0 1 -1
     */
    public static function delete($orderId) {
        $db = Db::get_instance();
        ## $status = $db->query("SELECT order_state FROM `fac_consumer_order` WHERE consumer_order_id = $orderId;");
        $res = $db->query("DELETE FROM `fac_consumer_order_item` WHERE consumer_order_id = $orderId;");
        $res1 = $db->query("DELETE FROM `fac_consumer_order` WHERE consumer_order_id = $orderId;");
        return $res && $res1;
    }

}
